import type { VNode } from 'vue';
import { defineComponent, h, reactive, createVNode, render } from 'vue';
import { Spin } from 'ant-design-vue';
import { LoadingProps } from './types';
export function createLoading(props: LoadingProps, target: HTMLElement = document.body) {
  let vm: Nullable<VNode> = null;
  const { absolute, ...LoadProps } = props;
  const data = reactive({
    delay: 200,
    ...(LoadProps as LoadingProps),
  });
  const LoadingWrap = defineComponent({
    render() {
      return h(Spin, { class: { 'loading-absolute': absolute }, ...data });
    },
  });
  vm = createVNode(LoadingWrap);
  render(vm, document.createElement('div'));
  function close() {
    if (vm?.el && vm.el.parentNode) {
      vm.el.parentNode.removeChild(vm.el);
    }
  }

  function open(target: HTMLElement = document.body) {
    if (!vm || !vm.el) {
      return;
    }
    target.appendChild(vm.el as HTMLElement);
  }

  if (target) {
    open(target);
  }
  return {
    vm,
    close,
    open,
    setTip: (tip: string) => {
      data.tip = tip;
    },
    setSpinning: (spinning: boolean) => {
      data.spinning = spinning;
    },
    get spinning() {
      return data.spinning;
    },
    get $el() {
      return vm?.el as HTMLElement;
    },
  };
}
